import numpy as np
import cv2 as cv

state = {
    'H': 0,
    'S': 0,
    'V': 0,
    'switch': 0
}


def create_callback(key):
    def callback(value):
        state[key] = value

    return callback


def create_interface():
    img = np.zeros((300, 512, 3), dtype=np.uint8)
    cv.namedWindow('HSV Picker')

    cv.createTrackbar('H (0-179)', 'HSV Picker', 0, 179, create_callback('H'))
    cv.createTrackbar('S (0-255)', 'HSV Picker', 0, 255, create_callback('S'))
    cv.createTrackbar('V (0-255)', 'HSV Picker', 0, 255, create_callback('V'))
    cv.createTrackbar('OFF/ON', 'HSV Picker', 0, 1, create_callback('switch'))

    return img


def main():
    img = create_interface()

    while True:
        if state['switch']:
            # 修正重点：创建正确的3通道HSV图像格式
            hsv = np.zeros((1, 1, 3), dtype=np.uint8)
            hsv[0, 0] = [state['H'], state['S'], state['V']]
            bgr = cv.cvtColor(hsv, cv.COLOR_HSV2BGR)[0, 0].tolist()
            img[:] = bgr
        else:
            img[:] = 0

        cv.imshow('HSV Picker', img)

        if cv.waitKey(1) == 27:
            break

    cv.destroyAllWindows()


if __name__ == '__main__':
    main()